package com.ict.web.rabbitMqConfig;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ict.common.core.domain.entity.SysDept;
import com.ict.common.utils.StringUtils;
import com.ict.common.utils.uuid.IdUtils;
import com.ict.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 同步部门信息（全量同步）
 * @author xc
 */
@RestController
@RequestMapping("/dept")
public class RefreshDept {

    public static JSONArray  tableData = new JSONArray ();
    public static JSONObject itemObj = new JSONObject();

    @Autowired
    private ISysDeptService deptService;
    /**
     * 获取建设单位和所属部门
     */
    @Transactional(rollbackFor = Exception.class)
    @GetMapping(value = "/get")
    public void getInfo()
    {
        JSONObject jsonDept = new JSONObject();
        jsonDept.put("departIds", null);
        HashMap<String, String> headersDept = new HashMap<>();
        headersDept.put("appCode", "smartcity_user_sync");
        headersDept.put("apiCode", "API_CODE_1630029712265597200");
        headersDept.put("apiVersion", "1.0.0");
        headersDept.put("apiVersion", "1.0.0");
        headersDept.put("format", "restful");
        headersDept.put("Content-Type", "application/json");
        String depetList = HttpUtil.createGet("http://23.99.215.138:21100/rest").addHeaders(headersDept).form(jsonDept).execute().body();
        JSONObject obj= JSONObject.parseObject(depetList);
        String json = obj.getJSONObject("result").getJSONArray("result").toString();
        JSONArray jsonArray = JSONArray.parseArray(json);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            itemObj = JSONObject.parseObject(itemObj.toJSONString());
            itemObj.put("id",jsonObject.getString("id"));
            itemObj.put("departName",jsonObject.getString("departName"));
            itemObj.put("departOrder",jsonObject.getString("departOrder"));
            itemObj.put("parentId",jsonObject.getString("parentId"));
            itemObj.put("departNameAbbr",jsonObject.getString("departNameAbbr"));
            itemObj.put("orgCategory",jsonObject.getString("orgCategory"));
            itemObj.put("title",jsonObject.getString("title"));
            itemObj.put("orgType",jsonObject.getString("orgType"));
            itemObj.put("orgCode",jsonObject.getString("orgCode"));
            itemObj.put("delFlag",jsonObject.getString("delFlag"));
            itemObj.put("updateTime",jsonObject.getString("updateTime"));
            itemObj.put("createTime",jsonObject.getString("createTime"));
            tableData.add(itemObj);
            JSONArray children = jsonArray.getJSONObject(i).getJSONArray("children");
            getChildren(children);
        }
        System.out.print(tableData);
        List<DeptDomain> deptDomains = tableData.toJavaList(DeptDomain.class);
        tableData=new JSONArray();
        List<SysDept> sysDeptList = deptService.selectLastDept();
        List<DeptDomain> collect = deptDomains.stream().filter(
                s->sysDeptList.stream()
                        .map(SysDept::getFormerId)
                        .noneMatch(a-> Objects.deepEquals(s.getId(),a)))
                .collect(Collectors.toList());
        List<SysDept> list = new ArrayList<>();
        collect.stream().forEach(s->{
            SysDept dept = new SysDept();
            dept.setDeptId(IdUtils.snowId());
            dept.setDeptName(s.getDepartName());
            dept.setOrderNum(s.getDepartOrder());
            dept.setStatus("0");
            dept.setDelFlag("0");
            dept.setOrgCategory(s.getOrgCategory());
            dept.setFormerId(s.getId());
            dept.setFormerParentId(s.getParentId());
            SysDept parentDept = deptService.selectDept(s.getParentId());
            if(StringUtils.isNotNull(parentDept)){
                dept.setParentId(parentDept.getDeptId());
                String ancestors = parentDept.getAncestors();
                dept.setAncestors(ancestors+","+parentDept.getDeptId());
            }
            deptService.insertDept(dept);
            list.add(dept);
        });
    }


    public static void getChildren(JSONArray children){
        for (int i = 0; i < children.size(); i++) {
            JSONObject jsonObject = children.getJSONObject(i);
            JSONArray children1 = jsonObject.getJSONArray("children");
            itemObj = JSONObject.parseObject(itemObj.toJSONString());
            itemObj.put("id",jsonObject.getString("id"));
            itemObj.put("departName",jsonObject.getString("departName"));
            itemObj.put("departOrder",jsonObject.getString("departOrder"));
            itemObj.put("parentId",jsonObject.getString("parentId"));
            itemObj.put("departNameAbbr",jsonObject.getString("departNameAbbr"));
            itemObj.put("orgCategory",jsonObject.getString("orgCategory"));
            itemObj.put("title",jsonObject.getString("title"));
            itemObj.put("orgType",jsonObject.getString("orgType"));
            itemObj.put("orgCode",jsonObject.getString("orgCode"));
            itemObj.put("delFlag",jsonObject.getString("delFlag"));
            itemObj.put("updateTime",jsonObject.getString("updateTime"));
            itemObj.put("createTime",jsonObject.getString("createTime"));
            if(children1 != null && children1.size() > 0){
                //有子节点，递归
                tableData.add(itemObj);
                getChildren(children1);
            }else{//无子节点
                tableData.add(itemObj);
                continue;
            }
            itemObj = new JSONObject();

        }
    }

}
